package com.MutiModule.common.treeNode;

import java.util.ArrayList;
import java.util.List;

import com.MutiModule.common.vo.TreeNode;

/**
 * 将实体类list集合 转换为树结构；
 * @author alexgaoyh
 *
 */
public class ResourceToTreeNodeConvert {

	public static List<TreeNode> convertResourceListToTreeNodeList(List<Resource> root, 
			List<Resource> nodes) {
		List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
		
		for(Resource _node : root) {
			TreeNode treeNode = getExtTree(_node , nodes);
			treeNodeList.add(treeNode);
		}
		return treeNodeList;
	}
	
	public static List<Resource> getRootNodesList(List<Resource> list) {
		//获取到所有顶级菜单节点
		List<Resource> rootResourceList = new ArrayList<Resource>();
		for(Resource _ztree : list ) {
			if(_ztree.getParentId() == null) {
				rootResourceList.add(_ztree);
			}
		}
		return rootResourceList;
	}
	
	public static TreeNode getExtTree(Resource node, List<Resource> list){
		TreeNode tree = new TreeNode();
		tree.setId(node.getId());
		tree.setParentId(node.getParentId() + "");
		tree.setText(node.getName());
		
		List<Resource> childList = getChildList(node, list);
		
		if (childList.size() > 0) {
			List<TreeNode> lt = new ArrayList<TreeNode>();
			for(Resource m : childList){
				lt.add(getExtTree(m, list));
			}
			tree.setChildren(lt);
		}
		return tree;
	}
	
	
	/**
	 * 从 list 整体集合中获取 node 的所有子元素
	 * @param node	某个特定节点，返回此节点下的所有子节点
	 * @param list	所有节点集合
	 * @return
	 */
	protected static List<Resource> getChildList(Resource node, List<Resource> list) {
		List<Resource> resultResourceList = new ArrayList<Resource>();
		for( Resource _zTreeNodes : list) {
			if(_zTreeNodes.getParentId() != null && node.getId() != null && _zTreeNodes.getParentId().longValue() == node.getId().longValue()) {
				resultResourceList.add(_zTreeNodes);
			}
		}
		return resultResourceList;
	}
}
